package com.dog.basics.sms.impl;


import cn.hutool.core.collection.CollUtil;
import com.dog.basics.SmsEntity.SmsParameter;
import com.dog.basics.SmsResult.SmsSendResult;
import com.dog.basics.sms.SmsSender;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 阿里云短信发送器
 *
 * @author Guo
 * @date 2019年4月30日
 */
@Log4j2
@Component
@Data
@ConfigurationProperties(prefix = "user.huyi.smscode")
//@ConditionalOnProperty(name = "flag", havingValue = "true")
public class HuYiSmsSender implements SmsSender {
    private String accessKeyId;
    private String accessKeySecret;
    private String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";

    @Override
    public SmsSendResult send(SmsParameter parameter) {
        SmsSendResult sendResult = new SmsSendResult();
         String content = new String("您的验证码是：" + parameter.getParams() + "。请不要把验证码泄露给其他人。");
        try {

            Map<String, Object> formDto = CollUtil.newHashMap(4);
            formDto.put("account", accessKeyId);
            formDto.put("password", accessKeySecret);
            formDto.put("mobile", parameter.getPhoneNumbers());
            formDto.put("content", content);
            // 头信息，多个头信息多次调用此方法即可
            String SubmitResult = cn.hutool.http.HttpUtil.post(Url, formDto);
            //String SubmitResult = method.getResponseBodyAsString();
            //System.out.println(SubmitResult);

            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();

            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            System.out.println(code);
            System.out.println(msg);
            System.out.println(smsid);

            if ("2".equals(code)) {
                sendResult.setSuccess(Boolean.TRUE);
                sendResult.setMessage(msg);
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sendResult.setSuccess(Boolean.FALSE);
            sendResult.setMessage("发送短信失败!");
        }
        return sendResult;
    }

}
